<?php

class UserController extends Zend_Controller_Action
{

  public function init()
  {
      /* Initialize action controller here */
    $this->mysession = new Zend_Session_Namespace('mysession');

  }


  public function loginAction()
  {
    if (Zend_Auth::getInstance()->hasIdentity()) {
      $this->_redirect('index/search');
      exit;
    }

    if ($this->_request->isPost()) {

      $data=$this->_request->getPost();
      if(isset($data['uname'])&&isset($data['password'])&&!empty($data['uname'])&&!empty($data['password']))
      {
        // get the default db adapter
        $db = Zend_Db_Table::getDefaultAdapter();
        //create the auth adapter
        $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'admin_users','uname', 'password');
        //set the username and password
        $authAdapter->setIdentity(addslashes(trim($data['uname'])));
        $authAdapter->setCredential(md5(addslashes(trim($data['password']))));

        $select = $authAdapter->getDbSelect();
        $select->where("status = '1'");


        //authenticate
        $result = $authAdapter->authenticate();

        if ($result->isValid()) {

          $auth = Zend_Auth::getInstance();
          $storage = $auth->getStorage();
          $storage->write($authAdapter->getResultRowObject(array('uname','added_date')));

          $authSession = new Zend_Session_Namespace('Zend_Auth');
          $authSession->setExpirationSeconds(60*10);

          $this->_redirect('Index/index');
          exit;
        } else {
          $this->view->loginMessage = "Sorry, your username or password is incorrect";
        }
      } else {
            $this->view->loginMessage = "Invalid username or password.";
      }
    }
  }

  public function logoutAction()
  {
    Zend_Auth::getInstance()->clearIdentity();
    $session = new Zend_Session_Namespace();
     $this->_redirect('user/login');
  }
}
